<template>
  <ui-page class="container">
    <!-- table -->
    <ui-table v-bind="table.config" ref="table" class="content_container" :params="{tenantId: userInfo.tenantId}"
              @select-change="onSelectTableEntity">
      <!--   查询   -->
      <template v-slot:search-bar>
        <ui-table-select v-model="table.model.select" :reset="true">
          <ui-table-select-item name="employeeId" label="员工编号" placeholder="请输入员工编号" show-label type="number"
                                start-null/>
          <ui-table-select-item name="name" label="姓名" placeholder="请输入姓名" show-label type="text"
                                :show-word-limit="false"/>
          <ui-table-select-item name="gender" label="性别" placeholder="请输入性别" show-label type="select" :data="genderList"
                                start-null/>
          <ui-table-select-item name="depId" label="所属部门" placeholder="请输入所属部门" show-label type="select"
                                :data="departmentList" :props="{value: 'id', label: 'name'}" start-null/>
          <ui-table-select-item name="position" label="职位" placeholder="请输入职位" show-label type="select" :data="positionList"
                                :show-word-limit="false"/>
          <ui-table-select-item name="hireDate" label="入职时间" placeholder="请选择入职时间" show-label type="datetimerange"
                                start-null/>
          <ui-table-select-item name="status" label="在职状态" placeholder="请选择在职状态" show-label :data="statusList"
                                type="select" start-null/>
        </ui-table-select>
      </template>
      <!--   操作   -->
      <template v-slot:tool-bar>
        <el-button type="primary" icon="el-icon-plus" @click="handleEntityCreate">新增</el-button>
        <el-button type="primary" icon="el-icon-printer" @click="handleEntityExport">导出</el-button>
      </template>
      <ui-table-column label="序号" type="index" width="60px"/>
      <ui-table-column prop="employeeId" label="员工编号" min-width="120"/>
      <ui-table-column prop="name" label="姓名" min-width="120"/>
      <ui-table-column prop="genderText" label="性别" min-width="120"/>
      <ui-table-column prop="departmentName" label="所属部门" min-width="120"/>
      <ui-table-column prop="positionText" label="职位" min-width="120"/>
      <ui-table-column prop="phone" label="联系方式" min-width="120"/>
      <ui-table-column prop="hireDate" label="入职时间" min-width="200"/>
      <ui-table-column prop="address" label="住址" min-width="200"/>
      <ui-table-column prop="statusText" label="就职状态" min-width="120">
        <template v-slot:default="{row}">
            <span :style="{color: row.statusText === '在职' ? 'green' : 'red'}">
              {{ row.statusText }}
            </span>
        </template>
      </ui-table-column>
      <ui-table-column type="action" :buttons="table.buttons" :resizable="false"/>
      <!--   分页   -->
      <template v-slot:footer-bar>
        <ui-table-pagination/>
      </template>
    </ui-table>
    <!-- form -->
    <ui-form-dialog ref="form" :title="form.title" :url="form.url" :loading="entityGetLoading"
                    :visible.sync="form.visible" class="entity-form" @after-submit="afterFormSubmit">
      <ui-form-item label="ID" name="id" type="hidden"/>
      <ui-form-item label="旧部门Id" name="oldDepId" type="hidden" v-if="!form.isCreate" />
      <ui-form-item name="name" label="姓名" type="text" vtype="required"/>
      <ui-form-item name="gender" label="性别" type="select" :data="genderList" vtype="required"/>
      <ui-form-item name="departmentId" label="所属部门" type="select" :data="departmentList"
                    :props="{value: 'id', label: 'name'}" vtype="required"/>
      <ui-form-item name="position" label="职位" type="select" :data="positionList" vtype="required"/>
      <ui-form-item name="phone" label="联系方式" type="text" vtype="required"/>
      <ui-form-item name="hireDate" label="入职时间" type="datetime" vtype="required"/>
      <ui-form-item name="address" label="住址" type="text" vtype="required"/>
      <ui-form-item name="status" label="在职状态" type="select" :data="statusList" vtype="required"/>
    </ui-form-dialog>
  </ui-page>
</template>
<script>
import {mapState} from 'vuex';
import to from "await-to-js";

const EntEmployee = {
  API: {
    create: '/Ent/EntEmployee/create',
    update: '/Ent/EntEmployee/update',
    delete: '/Ent/EntEmployee/delete',
    select: '/Ent/EntEmployee/select',
    export: '/Ent/EntEmployee/export',
    createList: '/Ent/EntEmployee/createList',
    updateList: '/Ent/EntEmployee/updateList',
    deleteList: '/Ent/EntEmployee/deleteList',
    selectList: '/Ent/EntEmployee/selectList',
    selectPage: '/Ent/EntEmployee/selectPage',
  },
  data() {
    return {
      api: EntEmployee.API,
      table: {
        config: {
          url: EntEmployee.API.selectPage,
        },
        model: {
          select: {},
        },
        buttons: [
          () => ({text: '修改', handle: this.handleEntityUpdateRow}),
          () => ({text: '删除', handle: this.handleEntityDeleteRow}),
        ],
      },
      form: {
        isCreate: true,
        title: '新增',
        url: EntEmployee.API.create,
        visible: false,
        rules: {},
      },
      genderList: [{value: 1, label: '男'}, {value: 2, label: '女'}],
      positionList: [{value: 1, label: '员工'}, {value: 2, label: '经理'}, {value: 3, label: '主管'}],
      statusList: [{value: 0, label: '在职'}, {value: 1, label: '离职'}],
      departmentList: [],
      oldDepId: null
    };
  },
  computed: {
    ...mapState(['userInfo']),
  },
  mounted() {
    this.getDepartment()
  },
  methods: {
    onSelectTableEntity(selects) {
      if (selects.length <= 0) {
        return;
      }
      this.handleEntityUpdateRow(selects[selects.length - 1]);
    },
    handleEntityCreate() {
      this.form.isCreate = true;
      this.$refs.form.resetValues();
      this.form.title = '新增';
      this.form.url = this.api.create;
      this.form.visible = true;
    },
    handleEntityUpdate() {
      const sels = this.$refs.table.getSelection();
      if (sels.length !== 1) {
        this.$message.info('请选择要修改的数据');
        return;
      }
      this.handleEntityUpdateRow(sels[0]);
    },
    handleEntityDelete() {
      const sels = this.$refs.table.getSelection();
      if (sels.length <= 0) {
        this.$message.info('请选择要删除的数据');
        return;
      }
      this.deleteEntities(sels.map(item => item.id)).then(({success}) => {
        if (!success) {
          return;
        }
        this.reloadTable();
      });
    },
    handleEntityUpdateRow(row) {
      this.form.isCreate = false;
      this.form.title = '修改';
      this.form.url = this.api.update;
      this.form.visible = true;

      this.selectEntity(row.id).then(({success, data}) => {
        if (!success) {
          this.form.visible = false;
          return;
        }
        this.oldDepId = data.departmentId
        Object.assign(data, {oldDepId: this.oldDepId})
        console.log(data)
        this.$refs.form.resetValues(data);
      });
    },
    handleEntityDeleteRow(row) {
      this.deleteEntity(row.id).then(({success}) => {
        if (!success) {
          return;
        }
        this.reloadTable();
      });
    },
    async handleEntityExport() {
      const loading = this.$loading({text: '数据加载中..'});
      const url = this.api.export;
      // await this.$refs.table.exportEntity(url, '导出.xls');
      await this.exportEntity(url, '员工信息.xls');
      loading.close();
    },
    exportEntity(url, filename) {
      if (!url) {
        console.error(`请指定 export api 请求地址`);
        return;
      }
      const searchParams = this.$refs.table.getSearchParams();
      this.$axios.download(url, filename, {
        params: {...searchParams}
      });
    },
    reloadTable() {
      this.$refs.table && this.$refs.table.reload();
    },
    afterFormSubmit({success}) {
      if (!success) {
        return;
      }
      this.form.visible = false;
      this.reloadTable();
    },
    async getDepartment () {
      const tenantId = this.userInfo.tenantId
      const [, result] = await to(this.$axios.get(`/Ent/EntDepartment/selectList?tenantId=${tenantId}`))
      this.departmentList = result.data || []
      console.log(this.departmentList)
    },
  },
};
export default EntEmployee;
</script>
<style lang="less" scoped>
</style>
